package com.css.zfzx.sjcj.modules.qhsoildynamic.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.utils.BeanUtil;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.ServerUtil;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.QhDrillOverviewRepository;
import com.css.zfzx.sjcj.modules.qhdrilloverview.repository.entity.QhDrillOverviewEntity;
import com.css.zfzx.sjcj.modules.qhsitushearwave.repository.entity.QhSituShearWaveEntity;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.QhSoilDynamicNativeRepository;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.QhSoilDynamicRepository;
import com.css.zfzx.sjcj.modules.qhsoildynamic.repository.entity.QhSoilDynamicEntity;
import com.css.zfzx.sjcj.modules.qhsoildynamic.service.QhSoilDynamicService;
import com.css.zfzx.sjcj.modules.qhsoildynamic.viewobjects.QhSoilDynamicQueryParams;
import com.css.zfzx.sjcj.modules.qhsoildynamic.viewobjects.QhSoilDynamicVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author aa
 * @date 2020-11-13
 */
@Slf4j
@Service
public class QhSoilDynamicServiceImpl implements QhSoilDynamicService {

	@Autowired
    private QhSoilDynamicRepository qhSoilDynamicRepository;
    @Autowired
    private QhSoilDynamicNativeRepository qhSoilDynamicNativeRepository;
    @Autowired
    private QhDrillOverviewRepository qhDrillOverviewRepository;

    @Override
    public JSONObject queryQhSoilDynamics(QhSoilDynamicQueryParams queryParams, int curPage, int pageSize) {
        Page<QhSoilDynamicEntity> qhSoilDynamicPage = this.qhSoilDynamicNativeRepository.queryQhSoilDynamics(queryParams, curPage, pageSize);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(qhSoilDynamicPage);
        return jsonObject;
    }


    @Override
    public QhSoilDynamicEntity getQhSoilDynamic(String id) {
        QhSoilDynamicEntity qhSoilDynamic = this.qhSoilDynamicRepository.findById(id).orElse(null);
         return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSoilDynamicEntity saveQhSoilDynamic(QhSoilDynamicEntity qhSoilDynamic) {
        String uuid = UUIDGenerator.getUUID();
        qhSoilDynamic.setId(uuid);
        qhSoilDynamic.setCreateUser(PlatformSessionUtils.getUserId());
        qhSoilDynamic.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        qhSoilDynamic.setIsValid("1");
        qhSoilDynamic.setReviewStatus("0");
        qhSoilDynamic.setQualityinspectionStatus("0");
        this.qhSoilDynamicRepository.save(qhSoilDynamic);
        return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public QhSoilDynamicEntity updateQhSoilDynamic(QhSoilDynamicEntity qhSoilDynamic) {
        qhSoilDynamic.setUpdateUser(PlatformSessionUtils.getUserId());
        qhSoilDynamic.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        String id = qhSoilDynamic.getId();
        QhSoilDynamicEntity one = qhSoilDynamicRepository.findById(id).get();
        BeanUtil.copyPropertiesIgnoreNull(qhSoilDynamic, one);
        this.qhSoilDynamicRepository.save(one);
        return qhSoilDynamic;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteQhSoilDynamics(List<String> ids) {
        List<QhSoilDynamicEntity> qhSoilDynamicList = this.qhSoilDynamicRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(qhSoilDynamicList) && qhSoilDynamicList.size() > 0) {
            for(QhSoilDynamicEntity qhSoilDynamic : qhSoilDynamicList) {
                this.qhSoilDynamicRepository.delete(qhSoilDynamic);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void submitQhSoilDynamics(String ids) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSoilDynamicEntity> qhDrillOverviewList = this.qhSoilDynamicRepository.findAllById(idList);
        if(!PlatformObjectUtils.isEmpty(qhDrillOverviewList) && qhDrillOverviewList.size() > 0) {
            for(QhSoilDynamicEntity qhDrillOverview : qhDrillOverviewList) {
                qhDrillOverview.setUpdateUser(PlatformSessionUtils.getUserId());
                qhDrillOverview.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                qhDrillOverview.setReviewStatus("1");
                this.qhSoilDynamicRepository.save(qhDrillOverview);
            }
        }
    }

    @Override
    public String importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            params.setTitleRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<QhSoilDynamicVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), QhSoilDynamicVO.class, params);
            List<QhSoilDynamicVO> list = result.getList();
            // 批量新增
            this.saveExcel(list);
            returnMsg.append("成功导入" + result.getList().size() + "条，失败" + result.getFailList().size() + "条<br/>");
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<QhSoilDynamicVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    QhSoilDynamicVO areaVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + areaVO.getRowNum() + "行" + areaVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return "导入失败，请检查数据正确性";
        }
    }

    @Override
    public String exportExcel(String ids, HttpServletResponse response) {
        List<String> idList = Arrays.asList(ids.split(","));
        List<QhSoilDynamicEntity> areaEntities = qhSoilDynamicRepository.findAllById(idList);

        return exportExcel(areaEntities,response);
    }

    @Override
    public String exportExcel(List<QhSoilDynamicEntity> areaEntities, HttpServletResponse response) {
        try {
            // 深拷贝
            ArrayList<QhSoilDynamicVO> vos = new ArrayList<>();
            for (QhSoilDynamicEntity areaEntity : areaEntities) {
                QhSoilDynamicVO vo = new QhSoilDynamicVO();
                BeanUtils.copyProperties(areaEntity, vo);
                vos.add(vo);
            }
            // 导出
            EasyPoiExcelUtil.exportExcel(vos, "土动力测试数据统计", "土动力测试数据", QhSoilDynamicVO.class, "土动力测试数据.xls", response);
            return "导出成功";
        } catch (Exception e) {
            e.printStackTrace();
            return e.getMessage();
        }
    }

    private void saveExcel(List<QhSoilDynamicVO> list) {
        for (int i = 0; i < list.size(); i++) {
//            QhSoilDynamicEntity areaEntity = new QhSoilDynamicEntity();
            QhSoilDynamicVO areaVO = list.get(i);
            QhSoilDynamicEntity areaEntity = qhSoilDynamicRepository.findById(areaVO.getId()).get();
            // 将VO数据映射拷贝到库表中
            BeanUtil.copyPropertiesIgnoreNull(areaVO, areaEntity);
            updateQhSoilDynamic(areaEntity);
        }
    }

    private void setCheckFields(Map<String,String> fields){
        fields.put("projectName","勘察工程名称");
        fields.put("drillCode","钻孔编号");
        fields.put("serialNumber","序号");
        fields.put("geotechnicalCode","岩土样品编号");
        fields.put("geotechnicalType","岩土样品类型");
        fields.put("geotechnicalStartDepth","岩土样品起始深度");
        fields.put("geotechnicalEndDepth","岩土样品结束深度");
        fields.put("modulusShearStrain005","模量比(G/Gmax)剪应变(γ)（10-4×0.05)");
        fields.put("modulusShearStrain010","模量比(G/Gmax)剪应变(γ)（10-4×0.10)");
        fields.put("modulusShearStrain050","模量比(G/Gmax)剪应变(γ)（10-4×0.50)");
        fields.put("modulusShearStrain100","模量比(G/Gmax)剪应变(γ)（10-4×1.00)");
        fields.put("modulusShearStrain500","模量比(G/Gmax)剪应变(γ)（10-4×5.00)");
        fields.put("modulusShearStrain1000","模量比(G/Gmax)剪应变(γ)（10-4×10.00)");
        fields.put("modulusShearStrain5000","模量比(G/Gmax)剪应变(γ)（10-4×50.00)");
        fields.put("modulusShearStrain10000","模量比(G/Gmax)剪应变(γ)（10-4×100.00)");
        fields.put("dampShearStrain005","阻尼比(λ)剪应变(γ)（10-4×0.05)");
        fields.put("dampShearStrain010","阻尼比(λ)剪应变(γ)（10-4×0.10)");
        fields.put("dampShearStrain050","阻尼比(λ)剪应变(γ)（10-4×0.50)");
        fields.put("dampShearStrain100","阻尼比(λ)剪应变(γ)（10-4×1.00)");
        fields.put("dampShearStrain500","阻尼比(λ)剪应变(γ)（10-4×5.00)");
        fields.put("dampShearStrain1000","阻尼比(λ)剪应变(γ)（10-4×10.00)");
        fields.put("dampShearStrain5000","阻尼比(λ)剪应变(γ)（10-4×50.00)");
        fields.put("dampShearStrain10000","阻尼比(λ)剪应变(γ)（10-4×100.00)");
        fields.put("province","省");
        fields.put("city","市");
        fields.put("area","区/县");
    }

    @Override
    public JSONObject dataQualityCheck(List<QhSoilDynamicEntity> qhSoilDynamicList){
        JSONObject res = new JSONObject();

        try {
            if(PlatformObjectUtils.isEmpty(qhSoilDynamicList) || qhSoilDynamicList.size() < 1) {
                return res;
            }

            Map<String, QhDrillOverviewEntity> drillCodeEntityMap = new HashMap<>();

            for(QhSoilDynamicEntity qhSoilDynamic : qhSoilDynamicList){
                //检查字段值不为空
                StringBuilder errorMsg = new StringBuilder();
                Map<String, String> methods = new HashMap<>();
                setCheckFields(methods);

                ServerUtil.checkFieldNull(qhSoilDynamic, methods, errorMsg);

                //检查天然密度 干密度
                if(PlatformObjectUtils.isEmpty(qhSoilDynamic.getNaturalDensity())){
                    float naturalDensity = Float.parseFloat(qhSoilDynamic.getNaturalDensity());
                    if(naturalDensity > 3){
                        ServerUtil.addErrorMsg(errorMsg,"天然密度","密度不超过3");
                    }
                }
                if(PlatformObjectUtils.isEmpty(qhSoilDynamic.getDryDensity())){
                    float dryDensity = Float.parseFloat(qhSoilDynamic.getDryDensity());
                    if(dryDensity > 3){
                        ServerUtil.addErrorMsg(errorMsg,"干密度","密度不超过3");
                    }
                }


                //检查岩土样品起始深度 岩土样品结束深度
                QhDrillOverviewEntity qhDrillOverviewEntity = null;
                String drillCode = qhSoilDynamic.getDrillCode();
                if(drillCodeEntityMap.containsKey(drillCode)){
                    qhDrillOverviewEntity = drillCodeEntityMap.get(drillCode);
                } else {
                    List<QhDrillOverviewEntity> qhDrillOverviewEntityList = this.qhDrillOverviewRepository.findByIsValidAndDrillCode("1",drillCode);
                    if(qhDrillOverviewEntityList.size() == 1){
                        qhDrillOverviewEntity = qhDrillOverviewEntityList.get(0);
                    }
                }
                if(qhDrillOverviewEntity != null){
                    float drillDepth = Float.parseFloat(qhDrillOverviewEntity.getDrillDepth());
                    float geotechnicalStartDepth = Float.parseFloat(qhSoilDynamic.getGeotechnicalStartDepth());
                    float geotechnicalEndDepth = Float.parseFloat(qhSoilDynamic.getGeotechnicalEndDepth());

                    if(geotechnicalStartDepth > drillDepth){
                        ServerUtil.addErrorMsg(errorMsg,"岩土样品起始深度","深度不超过终孔深度");
                    }
                    if(geotechnicalEndDepth > drillDepth){
                        ServerUtil.addErrorMsg(errorMsg,"岩土样品结束深度","深度不超过终孔深度");
                    }
                }

                //写入系统质检原因
                String strErrorMsg = errorMsg.toString();
                if(!strErrorMsg.isEmpty()) {
                    qhSoilDynamic.setQualityinspectionComments(strErrorMsg);
                    qhSoilDynamic.setQualityinspectionStatus("1");
                    qhSoilDynamic.setQualityinspectionResult("0");
                    this.updateQhSoilDynamic(qhSoilDynamic);

                    res.put(qhSoilDynamic.getId(),strErrorMsg);
                } else {
                    qhSoilDynamic.setQualityinspectionStatus("1");
                    qhSoilDynamic.setQualityinspectionResult("1");
                    this.updateQhSoilDynamic(qhSoilDynamic);
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
        }

        return res;
    }

    @Override
    public JSONObject dataQualityCheck(String drillCodes){
        List<String> idList = Arrays.asList(drillCodes.split(","));
        List<QhSoilDynamicEntity> qhSoilDynamicList = this.qhSoilDynamicRepository.findByIsValidAndDrillCodeIn("1",idList);

        return dataQualityCheck(qhSoilDynamicList);
    }
}
